#pragma once
#include <exception>
#include <pthread.h>
#include <semaphore.h>
using namespace std;

class Sem
{
public:
    Sem()
    {
        if (sem_init(&sem, 0, 0) != 0)
        {
            throw exception();
        }
    }

    ~Sem()
    {
        sem_destroy(&sem);
    }

    //P操作
    bool wait()
    {
        return sem_wait(&sem) == 0;
    }

    //V操作
    bool post()
    {
        return sem_post(&sem) == 0;
    }
private:
    sem_t sem;
};

class Locker
{
public:
    Locker()
    {
        if (pthread_mutex_init(&mtx, NULL) != 0)
        {
            throw exception();
        }
    }

    ~Locker()
    {
        pthread_mutex_destroy(&mtx);
    }

    //加锁
    bool lock()
    {
        return pthread_mutex_lock(&mtx) == 0;
    }

    //解锁
    bool unlock()
    {
        return pthread_mutex_unlock(&mtx) == 0;
    }
private:
    pthread_mutex_t mtx;
};

class Cond
{
public:
    Cond()
    {
        if (pthread_mutex_init(&mtx, NULL) != 0)
        {
            throw exception();
        }
        if (pthread_cond_init(&cond, NULL) != 0)
        {
            pthread_mutex_destroy(&mtx);
            throw exception();
        }
    }

    ~Cond()
    {
        pthread_mutex_destroy(&mtx);
        pthread_cond_destroy(&cond);
    }

    bool wait()
    {
        int ret = 0;
        pthread_mutex_lock(&mtx);
        pthread_cond_wait(&cond, &mtx);
        pthread_mutex_unlock(&mtx);
        return ret == 0;
    }

    bool signal()
    {
        return pthread_cond_signal(&cond) == 0;
    }
private:
    pthread_mutex_t mtx;
    pthread_cond_t cond;
};